﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Happy.Domain.CommonModel.TreeLike
{
    /// <summary>
    /// 泛型版本的树形聚合根。
    /// </summary>
    public abstract class TreeNode<TId> : AggregateRoot<TId>
        where TId : struct
    {
        /// <summary>
        /// 构造方法。
        /// </summary>
        protected TreeNode() { }

        /// <summary>
        /// 构造方法。
        /// </summary>
        protected TreeNode(TId id)
            : base(id)
        {
            this.AsRoot();
        }

        /// <summary>
        /// 构造方法。
        /// </summary>
        protected TreeNode(TId id, TreeNode<TId> parent)
            : base(id)
        {
            this.MoveTo(parent);
        }

        /// <summary>
        /// 父节点ID。
        /// </summary>
        public TId? ParentId { get; protected set; }

        /// <summary>
        /// 节点在树中的路径，如：/A/B/C/D，包含自己。
        /// </summary>
        public string NodePath { get; protected set; }

        /// <summary>
        /// 移动节点。
        /// </summary>
        protected internal void MoveTo(TreeNode<TId> parent)
        {
            this.ParentId = parent.Id;
            this.NodePath = string.Format("{0}{1}{2}",
                parent.NodePath,
                TreeNodeConstant.NodePathSeparator,
                this.Id);
        }

        /// <summary>
        /// 设置为根节点。
        /// </summary>
        protected internal void AsRoot()
        {
            this.ParentId = null;
            this.NodePath = string.Format("{0}{1}{2}",
                String.Empty,
                TreeNodeConstant.NodePathSeparator,
                this.Id);
        }
    }
}
